package com.langsin.blog.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.langsin.blog.domain.User;

import java.io.IOException;

public class JsonSerializeUtil {
    //Data Binding 将对象转化为Json字符串
    public static String convertToJsonString(Object obj){

        ObjectMapper mapper = new ObjectMapper();
        String result = "";
        //json输出带格式,增加可读性，生产中会增加json内容
//        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

        //忽略空值
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

        try {
            result = mapper.writeValueAsString(obj);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    //将Json字符串反序列化为User对象
    public static User convertJsonStringToUser(String jsonStr){

        ObjectMapper mapper = new ObjectMapper();
        User user = null;

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        try {
            user = mapper.readValue(jsonStr, User.class);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return user;
    }
}

